package de.lmu.ifi.pst.uwejsf.framework;

import java.util.Map;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;

import org.apache.commons.beanutils.PropertyUtils;

public class OGNLContentSelector implements ContentSelector {

	private String name;
	private Expression expression;
	private String sourceContentLink;

	@Override
	public Object getContent(ExpressionContextProvider contextProvider) {

		if (expression == null)
			return null;
		if (expression.getExpression() == null)
			return null;
		if (expression.getContextBeanName() == null) {
			if (expression.getExpression().trim().equals("UWEContent"))
				return null;
		}
		ScriptEngine engine = contextProvider.getScriptEngineByName("ognl");
		Map<String, Object> beans = contextProvider.getManagedBeans();
		String usedContentInLink = sourceContentLink == null ? expression
				.getContentInLink() : sourceContentLink;
		Object contextBean = null;
		if (expression.getContextBeanName() != null)
			contextBean = beans.get(expression.getContextBeanName());
		Object contextObject = contextBean;
		if (usedContentInLink != null && contextBean != null) {
			try {
				contextObject = PropertyUtils.getProperty(contextBean,
						"content_" + usedContentInLink);
			} catch (Exception e) {
				throw new NavigationException("Couldn't get direct content "
						+ usedContentInLink + " for bean "
						+ expression.getContextBeanName(), e);
			}
		}

		ScriptContext scriptContext = contextProvider
				.createScriptContext(contextObject);
		Object result = null;
		try {
			result = engine.eval(expression.getExpression(), scriptContext);
		} catch (Exception e) {
			throw new NavigationException("Couldn't evaluate OGNL script: "
					+ expression.getExpression(), e);
		}

		return result;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public Expression getExpression() {
		return expression;
	}

	@Override
	public String getSourceContentInLink() {
		return sourceContentLink;
	}

	@Override
	public void setExpression(Expression expression) {
		this.expression = expression;

	}

	@Override
	public void setSourceContentInLink(String sourceContentInLink) {
		this.sourceContentLink = sourceContentInLink;

	}

}
